package com.enwayouli.controller;

import com.enwayouli.mapper.UserMapper;
import com.enwayouli.pojo.User;
import com.enwayouli.util.JwtUtil;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@CrossOrigin
@RestController
@ResponseBody
public class UserController {
    private Map<String,Integer> emailCode = new HashMap();
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/login")
    public User login(String username, String password){
        User user = userMapper.login(username,password);
        if (user!=null){
            user.setToken(JwtUtil.createToken());
            return user;
        }
        return null;
    }
    @RequestMapping("/register")
    public String register(String username, String password, String email, int code){
        if (code==0){
            return "验证码错误";
        }
        if (emailCode.get(email)==null){
            return "请获取验证码";
        } else if (emailCode.get(email) != code){
            return "验证码错误";
        }
        try {
            int state = userMapper.register(username,password,email);
            if (state>0){
                emailCode.remove(email);
                return "注册成功";
            }
        } catch (Exception e){
            return "注册失败,用户名和邮箱必须唯一";
        }
        return "注册失败";
    }
    @RequestMapping("/getCode")
    public void getCodeByEmail(String email){
        try {
            getCode(email);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/session")
    public User testSession(HttpSession session){
        return (User) session.getAttribute("user");
    }
    @RequestMapping("/checkToken")
    public Boolean getUserSession(HttpServletRequest request){
        String token = request.getHeader("token");
        return JwtUtil.checkToken(token);
    }

    private void getCode(String targetEmail) throws Exception {
        //授权码   cxjgbainaoqbjbgh
        Properties prop = new Properties();
        prop. setProperty("mail.host", "smtp.qq.com");//设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp");//邮件发送协议
        prop.setProperty("mail.smtp.auth", "true");//需要验证用户名密码
        //关于QQ邮箱，还要设置SSL加密，加上以下代码即可
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put( "mail.smtp.ssl.enable", "true");
        prop.put( "mail.smtp.ssl.socketFactory", sf);

        //使用JavaMail发送邮件的6个步骤
        //1、创建定义整个应用程序所需的环境信息的Session对象

        //创建定义整个应用程序所需的环境信息的session对象
        Session session = Session.getDefaultInstance(prop,new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication( "1574311700@qq.com","cxjgbainaoqbjbgh");
            }
        });

        session.setDebug(true);
        //2、通过session得到transport对象
        Transport transport = session.getTransport();
        //3、使用邮箱的用户名和授权码连上邮件服务器
        transport.connect("smtp.qq.com","1574311700@qq.com","cxjgbainaoqbjbgh");
        //4、创建邮件
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("1574311700@qq.com"));//指明发件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(targetEmail));//指明收件人
        message.setSubject("验证码");//邮件主题
        int code = (int)(Math.random()*(9999-1000+1)+1000);
        message.setContent("你的验证码是"+code,"text/html;charset=utf8");
        //5、发送邮件
        transport.sendMessage(message, message.getAllRecipients());

        emailCode.put(targetEmail,code);
        //6、关闭链接
        transport.close();
    }

}
